package com.presto.directo.mvvm.view

import android.content.Intent
import android.os.Bundle
import android.text.InputFilter
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.widget.doOnTextChanged
import com.presto.directo.R
import com.presto.directo.base.BaseActivity
import com.presto.directo.databinding.ActivityCardAddBinding
import com.presto.directo.entity.CreditBankEntity
import com.presto.directo.mvvm.adapter.CARD_TYPES
import com.presto.directo.net.getHttpMap
import com.presto.directo.net.sign
import com.presto.directo.utils.*
import ru.whalemare.sheetmenu.SheetMenu

class CardAddActivity : BaseActivity() {

    private val binding by lazy { ActivityCardAddBinding.inflate(layoutInflater) }

    override val rootView: View
        get() = binding.root

    private val views by lazy { listOf(binding.tvChange, binding.etBankCardNum, binding.tvBank) }
    private var type = -1
    private var bank_code = ""
    private var bank_name = ""
    private var bankMap = mutableMapOf<String, CreditBankEntity?>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Af.show_add_card_page.track(this)
    }

    override fun initEvent() {
        views.forEach {
            it.doOnTextChanged { text, start, before, count ->
                if (type == 1 && it == binding.etBankCardNum) {
                    if (binding.etBankCardNum.text.toString().length >= 3) {
                        val cardNo = binding.etBankCardNum.text.toString().substring(0, 3)
                        val creditBankEntity = bankMap[cardNo]
                        if (creditBankEntity == null) {
                            getBank(cardNo)
                        } else {
                            bank_name = creditBankEntity.bankName
                            bank_code = creditBankEntity.bankCode
                            binding.tvBank.text = bank_name
                        }
                    } else {
                        bank_name = ""
                        bank_code = ""
                        binding.tvBank.text = bank_name
                    }
                }
                updateBtn()
            }
        }
        binding.tvChange.setOnClickListener {
            SheetMenu(
                actions = CARD_TYPES,
                onClick = {
                    if (it.id + 1 == type) return@SheetMenu
                    bank_code = ""
                    bank_name = ""
                    binding.etBankCardNum.setText("")
                    binding.tvBank.text = ""
                    type = it.id + 1
                    binding.tvChange.text = it.title
                    binding.tvBank.isClickable = type == 2
                    binding.tvBank.hint = if (type == 1) "" else getString(R.string.text_select_please)
                    binding.etBankCardNum.filters = arrayOf<InputFilter>(InputFilter.LengthFilter(if (type == 1) 18 else 16))
                    binding.tvLengthTips.text = if (type == 1) getString(R.string.text_bank_card_lenght2) else getString(R.string.text_bank_card_lenght1)
                },
                layoutProvider = MyLayoutProvider()
            ).show(this)
        }
        binding.tvBank.setOnClickListener {
            launcher.launch(Intent(this, BankListActivity::class.java))
        }
        binding.btnNext.setOnClickListener {
            Af.click_add_card.track(this)
            start(onNext = {
                showProgress()
                val map = getHttpMap()
                map["card_no"] = binding.etBankCardNum.text.toString()
                map["bank_code"] = bank_code
                map["card_type"] = type
                getApiService().addCard(map.sign(20)).getResultOrNull()
                Af.success_add_card.track(this)
                setResult(RESULT_OK)
                finish()
            }, onComplete = {
                dismissProgress()
            })
        }
    }

    private val launcher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
        if (it.resultCode != RESULT_OK) return@registerForActivityResult
        bank_name = it.data?.getStringExtra("bankName") ?: ""
        bank_code = it.data?.getStringExtra("bankCode") ?: ""
        binding.tvBank.text = bank_name
    }

    private fun getBank(cardNo: String) {
        start(onNext = {
            val map = getHttpMap()
            map["cardNo"] = cardNo
            val creditBankEntity = getApiService().queryCreditBank(map.sign(32)).getResultOrNull()
            bankMap[cardNo] = creditBankEntity
            if (type == 1 && binding.etBankCardNum.text.toString().length >= 3) {
                val currentCardNo = binding.etBankCardNum.text.toString().substring(0, 3)
                bankMap[currentCardNo]?.let {
                    bank_code = it.bankCode
                    bank_name = it.bankName
                    binding.tvBank.text = bank_name
                }
            }
        }, toast = false)
    }

    override fun updateBtn() {
        binding.btnNext.isEnabled = views.all { it.text.isNotBlank() }
    }

}